package com.hsy.crm.web.config;

import com.hsy.crm.web.domain.entity.Company;
import com.hsy.crm.web.domain.entity.User;
import com.hsy.crm.web.domain.po.login.LoginPo;
import com.hsy.crm.web.service.impl.CompanyService;
import com.hsy.crm.web.service.impl.UserService;
import com.hsy.crm.web.utils.Md5Utils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class ShiroRealm extends AuthorizingRealm {

	private Logger logger = LoggerFactory.getLogger(ShiroRealm.class);

	@Autowired
    UserService userService;

	@Autowired
	CompanyService companyService;

	/**
	 * 获取用户角色和权限
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		return null;
	}

	/**
	 * 登录认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		User user = (User) token.getPrincipal();
		logger.info("用户{}认证",user.getUsername());

        User dbUser = userService.selectForLogin(user);
        if (user != null && dbUser.getPassword().equals(Md5Utils.encrypt(user.getPassword()))) {
            dbUser.setPassword(null);

			Company company = new Company();
			company.setId(dbUser.getCompanyId());
			company.setCustomerId(dbUser.getCustomerId());
			company = companyService.selectByPrimaryKey(company);

			LoginPo loginPo = new LoginPo();
			loginPo.setCompanyId(company.getId());
			loginPo.setCompanyLogicalCode(company.getLogicalCode());
			loginPo.setCompanyName(company.getName());
			loginPo.setCompanyParentId(company.getParentId());
			loginPo.setCustomerId(dbUser.getCustomerId());
			loginPo.setUserId(String.valueOf(dbUser.getId()));
			loginPo.setUserName(dbUser.getUsername());
			loginPo.setName(dbUser.getName());

            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(loginPo,token.getCredentials(),this.getName());
            return info;
        }else{
            return null;
        }
	}

    @Override
    public boolean supports(AuthenticationToken var1){
	    return true;
    }

	@Override
	public String getName(){
		return "crmShiroRealm";
	}

}
